<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="题目内容" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入题目内容" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="课程分类" prop="categoryId">
              <el-select clearable v-model="queryParams.categoryId"  @change="typeHandleCourse($event)"  placeholder="请选择课程分类" class="w-full">
                <el-option
                  v-for="item in courseType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="关联课程" prop="courseId">
              <el-select clearable v-model="queryParams.courseId" placeholder="请选择关联课程" @change="searchCourse($event)" class="w-full">
                <el-option
                  v-for="item in courseOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

             <el-form-item label="关联视频" prop="videoId">
              <el-select clearable v-model="queryParams.videoId" placeholder="请选择关联视频" class="w-full">
                <el-option
                  v-for="item in searchVideoOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"/>
              </el-select>
              </el-form-item>
            <el-form-item label="题目类型" prop="type">
                <el-select clearable v-model="queryParams.type" placeholder="请选择题型" class="w-full" @keyup.enter="handleQuery">
                  <el-option label="单选题" value="0" />
                  <el-option label="多选题" value="1" />
                  <el-option label="判断题" value="2" />
                  <el-option label="主观题" value="3" />
                </el-select>
              </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bykt:simulation:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['bykt:simulation:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['bykt:simulation:remove']">删除</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="primary" plain icon="Download" @click="visibleHidden = true">导入文件</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleExport" v-hasPermi="['bykt:simulation:export']">导出模版</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="simulationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目内容" align="center" prop="title" />
        <el-table-column label="题目类型" align="center" prop="type" >
            <template #default="scope">
              <span>{{ scope.row.type == 0 ? '单选题' : scope.row.type == 1 ?'多选题' : scope.row.type == 2 ?'判断题':"主观题"}}</span>
            </template>
          </el-table-column>
        <el-table-column label="选项内容" align="center" prop="options" />
        <el-table-column label="正确答案" align="center" prop="answer" />
        <el-table-column label="解析" align="center" prop="analysis" />
        <el-table-column label="题库类型" align="center" prop="questionType">
            <template #default="scope">
              <span>习题</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bykt:simulation:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bykt:simulation:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="80%" append-to-body>
      <div v-if="!batchMode">
        <el-form ref="simulationFormRef" :model="form" :rules="rules" label-width="90px">
          <el-row :gutter="20">
            <el-col :span="8">

              <el-form-item label="关联课程" prop="courseId">
                    <el-select clearable v-model="form.courseId" placeholder="请选择关联课程" @change="handleCourseChange" class="w-full">
                      <el-option
                        v-for="item in courseOptions"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="关联视频" prop="videoId">
                    <el-select clearable v-model="form.videoId" placeholder="请选择关联视频" class="w-full">
                      <el-option
                        v-for="item in videoOptions"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="解析" prop="analysis">
                <el-input
                  v-model="form.analysis"
                  type="textarea"
                  placeholder="请输入解析内容"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                />
              </el-form-item>
              <el-form-item label="排序">
                  <el-input-number v-model="form.sort" :min="1" />
                </el-form-item>

            </el-col>
            <el-col :span="8">

              <el-form-item label="题目类型" prop="type">
                <el-select clearable v-model="form.type" placeholder="请选择题型" class="w-full" @change="handleTypeChange">
                  <el-option label="单选题" value="0" />
                  <el-option label="多选题" value="1" />
                  <el-option label="判断题" value="2" />
                  <el-option label="主观题" value="3" />
                </el-select>
              </el-form-item>

              <el-form-item label="题目内容" prop="title">
                <el-input
                  v-model="form.title"
                  type="textarea"
                  placeholder="请输入题目内容"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                />
              </el-form-item>

              <el-form-item label="正确答案" prop="answer">
                <el-input v-model="form.answer" placeholder="请输入正确答案" />
              </el-form-item>

            </el-col>
            <el-col :span="8">
              <el-form-item label="选项内容" prop="options">
                <template v-if="form.type === '0' || form.type === '1'">
                  <div v-for="(option, index) in optionsList" :key="index" class="mb-2 flex items-center">
                    <el-input v-model="option.key" placeholder="请输入选项内容" class="mr-2" />
                    <el-input v-model="option.value" placeholder="请输入选项标识" class="mr-2" />
                    <el-button type="danger" @click="removeOption(index)" :disabled="optionsList.length === 1">
                      删除
                    </el-button>
                  </div>
                  <el-button type="primary" @click="addOption">新增选项</el-button>
                </template>
                <el-input
                  v-else
                  v-model="form.options"
                  type="textarea"
                  placeholder="请输入选项内容（多个选项用|分隔）"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                />
              </el-form-item>
              <el-form-item label="图片" prop="image">
              <el-upload
                :headers="uploadHeaders"
                drag
                action="/dev-api/ossUpload/uploadImage"
                :on-progress="handleImageProgress"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
                :on-remove="handleImageRemove"
                :file-list="imageFileList"
                accept=".jpg,.png"
                list-type="picture-card"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>

                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon><zoom-in /></el-icon>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleImageRemove(file)"
                      >
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-col>
          </el-row>
        </el-form>

        <div class="flex justify-between mb-4">
          <div></div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm(1)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <ImportXlsxs :visible="visibleHidden" :url="url" @parentFunction="parentFunction"></ImportXlsxs>
  </div>
</template>

<script setup>
import { listExercise, getExerciseInfo, delExercise, addExercise, updateExercise,exportExercise } from '@/api/bykt/afterClassQuestions/index';
import { getCourseList ,getCategoryTypeList} from '@/api/bykt/course/index';
import { getVideoList } from '@/api/bykt/video/index';
import ImportXlsxs from '@/components/ImportXlsxs/index.vue';
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
const { proxy } = getCurrentInstance();
import { getToken } from '@/utils/auth';
import {useRouter} from 'vue-router'
const router = useRouter()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const simulationList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
// const coverFileList = ref([]);
const visibleHidden = ref(false)
const queryFormRef = ref();
const simulationFormRef = ref();
const url = ref('http://localhost/dev-api/bykt/exercise/courseExerciseImportData');
const dialog = reactive({
  visible: false,
  title: ''
});

const initFormData = {
  id: undefined,
  videoId: undefined,
  courseId: undefined,
  simulationId: undefined,
  title: undefined,
  type: undefined,
  options: undefined,
  answer: undefined,
  analysis: undefined,
  image: undefined,
  score: undefined,
}
const uploadHeaders = ref({
  'Authorization': `Bearer ` + getToken(), // JWT 示例
});
const data = reactive({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    videoId: undefined,
    courseId: undefined,
    simulationId: undefined,
    title: undefined,
    type: undefined,
    options: undefined,
    answer: undefined,
    analysis: undefined,
    image: undefined,
    score: undefined,
    params: {}
  },
  rules: {
    title: [
      { required: true, message: "题目内容不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "题目类型不能为空", trigger: "change" }
    ],
    answer: [
      { required: true, message: "正确答案不能为空", trigger: "blur" }
    ],
    courseId: [
      { required: true, message: "关联课程不能为空", trigger: "change" }
    ],
    videoId: [
      { required: true, message: "关联视频不能为空", trigger: "change" }
    ],
  }
});

const courseType=ref([]);
const courseOptions = ref([]);
const videoOptions = ref([]);
const imageProgress = ref(0)
const imageFileList = ref([])
const searchVideoOptions = ref([]);
const optionsList = ref([]);

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 添加监听题目类型变化的函数
const handleTypeChange = (value) => {
  if (value === '0' || value === '1') { // 单选题或多选题
    optionsList.value = [
      { key: '', value: '' }
    ];
  } else {
    optionsList.value = [];
  }
};

// 添加选项的函数
const addOption = () => {
  optionsList.value.push({ key: '', value: '' });
};

// 删除选项的函数
const removeOption = (index) => {
  optionsList.value.splice(index, 1);
};

// 转换选项为指定格式的函数
const formatOptions = () => {
  const formattedOptions = optionsList.value.map(item => ({
    id: item.value,
    text: item.key
  }));
  form.value.options = JSON.stringify(formattedOptions);
};



const parentFunction = (data) => {
  visibleHidden.value = false
  getList()
}

const fetchCourseList = async () => {
  try {
    const res = await getCourseList({});
    courseOptions.value = res.rows || [];

  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
};

const handleCourseChange = async (courseId) => {
  if (!courseId) {
    videoOptions.value = [];
    form.value.videoId = undefined;
    return;
  }
  try {
    const res = await getVideoList({ courseId });
    videoOptions.value = res.rows || [];
    form.value.videoId = undefined;
  } catch (error) {
    console.error("获取视频列表失败:", error);
  }
};

const searchCourse = async (courseId) => {
  if (!queryParams.value.courseId) {
    searchVideoOptions.value = [];
    queryParams.value.videoId = undefined;
    return;
  }
  try {
    const res = await getVideoList({ courseId });
    searchVideoOptions.value = res.rows || [];
    form.value.videoId = undefined;
  } catch (error) {
    console.error("获取视频列表失败:", error);
  }
}

const { queryParams, form, rules } = toRefs(data);
const props = defineProps({
  simulationId: {
    default: undefined
  },
  questionType:{
    default: undefined
  }
});

const getList = async () => {
  loading.value = true;
  const res = await listExercise({...queryParams.value,questionType:1});
  simulationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

const cancel = () => {
  reset();
  batchMode.value = false;
  dialog.visible = false;

}

const reset = () => {
  form.value = {...initFormData,
    questionType: 1
  };
  imageFileList.value = [];
  simulationFormRef.value?.resetFields();
}

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
  searchVideoOptions.value = [];
  fetchCourseList();
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const handleAdd = async () => {
  reset();
  batchMode.value = false;
  // 如果搜索条件中已选择了课程，则设置到表单中
  if (queryParams.value.courseId) {
    form.value.courseId = queryParams.value.courseId;
    // 获取该课程下的视频列表
    const res = await getVideoList({ courseId: queryParams.value.courseId });
    videoOptions.value = res.rows || [];
    // 如果搜索条件中已选择了视频，则设置到表单中
    if (queryParams.value.videoId) {
      form.value.videoId = queryParams.value.videoId;
    }
  }
  dialog.visible = true;
  dialog.title = "添加课后题";
}

// 在handleUpdate函数中添加图片回显逻辑
const handleUpdate = async (row) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getExerciseInfo(_id);
  Object.assign(form.value, res.data);

  // 如果是单选题或多选题，解析选项内容
  if (form.value.type === '0' || form.value.type === '1') {
    try {
      const options = JSON.parse(form.value.options || '[]');
      optionsList.value = options.map(item => ({
        key: item.text,
        value: item.id
      }));
    } catch (error) {
      optionsList.value = [{ key: '', value: '' }];
      console.error('解析选项失败:', error);
    }
  }
  // 如果有图片，设置图片列表
  if (form.value.image) {
    imageFileList.value = [{
      name: form.value.image.split('/').pop(),
      url: form.value.image
    }];
  }

  dialog.visible = true;
  dialog.title = "修改课后题";

  // 获取视频列表
  if (form.value.courseId) {
    const videoRes = await getVideoList({ courseId: form.value.courseId });
    videoOptions.value = videoRes.rows || [];
  }
}
const typeHandleCourse = async (categoryId) => {
  // console.log(categoryId)
  try {
    const res = await getCourseList({categoryId});
    queryParams.value.courseId = undefined;
    courseOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
}
const handleDelete = async (row) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('确认是否删除数据？').finally(() => loading.value = false);
  await delExercise(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

const handleExport = () => {
  proxy?.download('bykt/exercise/export', {
    ...queryParams.value
  }, `习题模版_${new Date().getTime()}.xlsx`)
}

const batchMode = ref(false);

const submitForm = async (questionType) => {
  simulationFormRef.value?.validate(async (valid) => {
    // console.log(form.value)
      if (valid) {
        if (form.value.type === '0' || form.value.type === '1') {
        formatOptions();
      }
        buttonLoading.value = true;
        try {
          if (form.value.id) {
            await updateExercise(form.value);
          } else {
            await addExercise({...form.value,questionType});
          }
          proxy?.$modal.msgSuccess("操作成功");
          dialog.visible = false;
          await getList();
        } catch (e) {
          console.error("操作失败:", e);
        } finally {
          buttonLoading.value = false;
        }
      }
    })
};

const handleImageSuccess = (response, file) => {
  imageProgress.value = 0;
  // 清空现有文件列表，然后添加新上传的文件
  imageFileList.value = [];
  // 添加延迟，确保DOM更新
  setTimeout(() => {
    imageFileList.value = [{
      name: file.name,
      url: response.data
    }];
    form.value.image = response.data;
  }, 10);
}

const handleImageRemove = () => {
  // 清空图片字段
  form.value.image = "";
  imageFileList.value = [];
}
const beforeImageUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!');
    return false;
  }
  if (form.value.image) {
    // 清空现有文件列表，以便上传新文件
    // imageFileList.value = [];
    // handleImageRemove()
  }
  return true;
}



const handleImageProgress = (event) => {
  imageProgress.value = event.percent;
}
// const handleExceed = (files, fileList) => {
//   form.value.image.clearFiles()
//   const file = files[0]
//   file.uid = genFileId()
//   form.value.image.handleStart(file)
// }
const fetchCourseTypeList = async () => {
  try {
    const res = await getCategoryTypeList({});
    courseType.value = res.rows || [];

  } catch (error) {
    console.error("获取课程分类列表失败:", error);
  }
};
onUpdated(() => {
  console.log('更新')
  const route = useRoute();
  const query = route.query;
  if (query.courseId) {
    queryParams.value.courseId = query.courseId
  }
  if (query.categoryId) {
    queryParams.value.categoryId = query.categoryId
  }
  if(query.videoId){
    queryParams.value.videoId = query.videoId
  }
  getList();
  fetchCourseList();
  fetchCourseTypeList()
  searchCourse()
  // 初始化选项列表
  if (form.value.type === '0' || form.value.type === '1') {
    try {
      const options = JSON.parse(form.value.options || '[]');
      optionsList.value = options.map(item => ({
        key: item.text,
        value: item.id
      }));
    } catch (error) {
      optionsList.value = [{ key: '', value: '' }];
      console.error('解析选项失败:', error);
    }
  }
})
onMounted(() => {
  // console.log()
  // 获取路由中的参数
  const route = useRoute();
  const query = route.query;
  if (query.courseId) {
    queryParams.value.courseId = query.courseId
  }
  if (query.categoryId) {
    queryParams.value.categoryId = query.categoryId
  }
  if(query.videoId){
    queryParams.value.videoId = query.videoId
  }
  getList();
  fetchCourseList();
  fetchCourseTypeList()
  searchCourse()
  // 初始化选项列表
  if (form.value.type === '0' || form.value.type === '1') {
    try {
      const options = JSON.parse(form.value.options || '[]');
      optionsList.value = options.map(item => ({
        key: item.text,
        value: item.id
      }));
    } catch (error) {
      optionsList.value = [{ key: '', value: '' }];
      console.error('解析选项失败:', error);
    }
  }
});
</script>
<style scoped>
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 64px;
  text-align: center;
}
</style>
